<?php 
include "../Lib/Common.php";
if (!isset($act)) {
	//---------= Start read schemal ----------------------------------------------------------------------------------------------
	// database constants
	// make sure the information is correct
	define("DB_SERVER", DATABASE_HOST);
	define("DB_USER", DATABASE_USER);
	define("DB_PASS", DATABASE_PASSWORD);
	define("DB_NAME", DATABASE_NAME);

	// connection to the database
	$dbhandle = mysql_connect(DB_SERVER, DB_USER, DB_PASS)
	   or die("Unable to connect to MySQL");

	// select a database to work with
	$selected = mysql_select_db(DB_NAME, $dbhandle)
	   or die("Could not select examples");

	// return all available tables 
	$result_tbl = mysql_query( "SHOW TABLES FROM ".DB_NAME, $dbhandle );

	$tables = array();
	while ($row = mysql_fetch_row($result_tbl)) {
	   $tables[] = $row[0];
	}
	$cols = 0;
	$tableName = $t;
	foreach ( $tables as $table ) {
	   $result_fld = mysql_query( "SHOW FIELDS FROM ".$table, $dbhandle );
	   if ($table == $t) {
		   while( $row1 = mysql_fetch_row($result_fld) ) {
			  if ($row1[3] != "PRI") { // PrimaryKey
				$cols++;
				if (!isset($firstInputField)) $firstInputField = $row1[0];
				${"FieldName$cols"} = $row1[0];
				${"Required$cols"}	= "false";
				${"MessageRQ$cols"}	= "";
				${"MaxLength$cols"}	= "";
				${"Size$cols"}		= "";
				${"IsComboBox$cols"}= "";
				${"ColumnTitle$cols"}	= $row1[0];
				${"Hidden$cols"}	= "false";
			  } else $primaryKeyName = $row1[0];
		   }
	   }
	}
}
mysql_close($dbhandle);
// init start values for creating admin page (List page)
if (!isset($pageName)) $pageName = "detail.php";
if (!isset($newTitle)) $newTitle= "Add new row";
if (!isset($editTitle)) $editTitle= "Edit information";
if (!isset($pageBack)) $pageBack = "list.php";
if (!isset($formName)) $formName = "frmMain";
if (!isset($tableName)) $tableName= "allfields";
if (!isset($primaryKeyName)) $primaryKeyName = "ID";
if (!isset($firstInputField)) $firstInputField= "FVarchar";
if (!isset($newObjStr)) $newObjStr = "";

if (!isset($cols)) $cols = 1;
if (isset($act) && $act=="CREATE") {
	//$columns[] = array("FieldName"=>"FVarchar", "Required"=>"true" /* Sort */, "MessageRQ"=>"Please enter FVarchar.", "MaxLength"=>"255", "Size"=>"50" /* Width */, "ColumnTitle"=>"FVarchar", "IsComboBox"=>"");
	//$columns[] = array("FieldName"=>"FNumeric", "Required"=>"false" /* Sort */, "MessageRQ"=>"", "MaxLength"=>"5", "Size"=>"10" /* Width */, "ColumnTitle"=>"FNumeric", "IsComboBox"=>"");
	//$columns[] = array("FieldName"=>"FDate", "Required"=>"false" /* Sort */, "MessageRQ"=>"", "MaxLength"=>"12", "Size"=>"25" /* Width */, "ColumnTitle"=>"FDate", "IsComboBox"=>"");
	for ($i=1; $i<=$cols;$i++) {
		$columns[] = array("FieldName"=>${"FieldName$i"}, "Required"=>${"Required$i"} /* Sort */, "MessageRQ"=>${"MessageRQ$i"}, 
						"MaxLength"=>${"MaxLength$i"} /* Width */, "Size"=>${"Size$i"} /* Align */, "ColumnTitle"=>${"ColumnTitle$i"}, "IsComboBox"=>${"IsComboBox$i"}, "Hidden"=>${"Hidden$i"});
	}

	// Create list page base on init values
	$filename = "./detailTR.tmpl";
	$handle = fopen($filename, "r");
	$tr = fread($handle, filesize($filename));
	fclose($handle);

	$filename = "./detailComboBoxTR.tmpl";
	$handle = fopen($filename, "r");
	$trComboBox = fread($handle, filesize($filename));
	fclose($handle);

	$filename = "./requireScript.tmpl";
	$handle = fopen($filename, "r");
	$js = fread($handle, filesize($filename));
	fclose($handle);


	$inputFields = $jsValid = "";
	for ($i=0; $i<count($columns); $i++) {
		$column = $columns[$i];
		if (trim($column["FieldName"])!="") {
			if ($column["Hidden"]=="false") {
				if ($column["IsComboBox"]!="")  $trContent = $trComboBox;
				else $trContent = $tr;
				$trContent = str_replace("{CT}", $column["ColumnTitle"], $trContent);
				if ($column["Required"]=="true") {
					$trContent = str_replace("{RQ}","*", $trContent);
					$jsContent = $js;
					if ($column["IsComboBox"]!="")
						$jsContent = str_replace("!_CF_hasValue(frm.{FN}, \"TEXT\")", "frm.{FN}.value=='' || frm.{FN}.value=='0'", $jsContent);
					$jsContent = str_replace("{FN}", $column["FieldName"], $jsContent);
					$jsContent = str_replace("{MR}", $column["MessageRQ"], $jsContent);
				} else {
					$jsContent = "";
					$trContent = str_replace("{RQ}","", $trContent);
				}
				$trContent = str_replace("{FN}", $column["FieldName"], $trContent);
				$trContent = str_replace("{S}", $column["Size"], $trContent);
				$trContent = str_replace("{M}", $column["MaxLength"], $trContent);
				if ($column["IsComboBox"]!="") {
					$args = explode(",", $column["IsComboBox"]);
					//echo GetComboBox($mainDB, usersObj::TableName(), "", "", "userOpt", "UserID", "Username", "Select one", "0", $defaultVAL, "");
					$comboTag = "include \"../../Entities/".$args[0]."Obj.php\"; include \"../../DAL/".$args[0]."DAL.php\"; echo GetComboBox(\$mainDB, ".$args[0]."Obj::TableName(), \"\", \"\", \"".$args[1]."\", \"".$args[2]."\", \"".$args[3]."\", \"Select one\", \"".($column["Required"]=="true"?"":"0")."\", \${\"".$args[1]."\"}, \"class='inputText'\");";
					$trContent = str_replace("{CBB}", "<?php  ".$comboTag."?>" , $trContent);
				}
			} else 	$trContent = "<input type=hidden name='".$column["FieldName"]."' value='<? echo \$".$column["FieldName"].";?>'>";
			
			$inputFields = $inputFields . $trContent;

			$jsValid = $jsValid.$jsContent;
		}
	}
	// get contents of listTemplate.php
	$filename = "./detailTemplate.tmpl";
	$handle = fopen($filename, "r");
	$contents = fread($handle, filesize($filename));
	fclose($handle);

	// Replace variables in contents
	$contents = str_replace("{pageName}", $pageName, $contents);
	$contents = str_replace("{editTitle}", $editTitle, $contents);
	$contents = str_replace("{newTitle}", $newTitle, $contents);
	$contents = str_replace("{pageBack}", $pageBack, $contents);
	$contents = str_replace("{formName}", $formName, $contents);
	$contents = str_replace("{tableName}", $tableName, $contents);
	$contents = str_replace("{primaryKeyName}", $primaryKeyName, $contents);
	$contents = str_replace("{firstInputField}", $firstInputField, $contents);
	$contents = str_replace("{newObjStr}", $newObjStr, $contents);
	$contents = str_replace("{inputFields}", $inputFields, $contents);
	$contents = str_replace("{jsValid}", $jsValid, $contents);

	$createdPage = $pageName;
	if (isset($createdDir) && $createdDir!="")
	{
		$dir = CreateDir($createdDir);
		$createdPage = $dir."/".$pageName;
	}
	$handle = fopen($createdPage, "w");

	fwrite($handle, $contents);

	fclose($handle);

	echo "Page Detail has created.";
}
?>
<script>
function AddColumn(col) {
	document.frmMain.cols.value = col;
	document.frmMain.submit();
}
function Create() {
	document.frmMain.act.value = "CREATE";
	document.frmMain.submit();
}
</script>
<form name=frmMain method=post>
<input type=hidden name=cols value="<?php  echo $cols;?>">
<input type=hidden name=act>
<b>CREATE PAGE DETAIL</b> <br>
<table>
	<tr>
		<td width="150">Page PHP name:</td>
		<td> <input type=text name=pageName value="<?php  echo $pageName;?>"></td>
	</tr>
	<tr>
		<td>New title:</td>
		<td><input type=text name=newTitle value="<?php  echo $newTitle;?>"></td>
	</tr>
	<tr>
		<td>Edit title:</td>
		<td><input type=text name=editTitle value="<?php  echo $editTitle;?>"></td>
	</tr>
	<tr>
		<td>Back page:</td>
		<td><input type=text name=pageBack value="<?php  echo $pageBack;?>"></td>
	</tr>
	<tr>
		<td>Form name:</td>
		<td><input type=text name=formName value="<?php  echo $formName;?>"></td>
	</tr>
	<tr>
		<td>Table name:</td>
		<td><input type=text name=tableName value="<?php  echo $tableName;?>"></td>
	</tr>
	<tr>
		<td>Primary key name: </td>
		<td><input type=text name=primaryKeyName value="<?php  echo $primaryKeyName;?>"></td>
	</tr>
	<tr>
		<td>First field input: </td>
		<td><input type=text name=firstInputField value="<?php  echo $firstInputField;?>"></td>
	</tr>
	<tr>
		<td>Param for Init object: </td>
		<td><input type=text name=newObjStr value="<?php  echo $newObjStr;?>"></td>
	</tr>
	<tr>
		<td>Created directory: </td>
		<td><input type=text name=createdDir value="<?php  echo $createdDir;?>"></td>
	</tr>
	<tr>
		<td></td>
		<td></td>
	</tr>
</table>
<b>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 
Field name &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
Column Title  &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
true/false &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
&nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; 
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; 
tablebName,optionName,keyField,displayField
</b><br>
<?php  for ($i=1; $i<=$cols; $i++) {?>
<b>Field <?php  echo $i;?>:</b><br>
&nbsp; &nbsp; Name: <input type=text name="FieldName<?php  echo $i;?>" value="<?php  if (isset(${"FieldName$i"})) echo ${"FieldName$i"};?>" style="width:100px"> &nbsp; 
	Title: <input type=text name=ColumnTitle<?php  echo $i;?> value="<?php  if (isset(${"ColumnTitle$i"})) echo ${"ColumnTitle$i"};?>"> &nbsp;
	Required: <input type=text name=Required<?php  echo $i;?> value="<?php  if (isset(${"Required$i"})) echo ${"Required$i"};?>" style="width:40px"> &nbsp; 
	Message REQ: <input type=text name=MessageRQ<?php  echo $i;?> value="<?php  if (isset(${"MessageRQ$i"})) echo ${"MessageRQ$i"};?>"> &nbsp; 
	Maxlen: <input type=text name=MaxLength<?php  echo $i;?> value="<?php  if (isset(${"MaxLength$i"})) echo ${"MaxLength$i"};?>" style="width:40px"> &nbsp; 
	Size: <input type=text name=Size<?php  echo $i;?> value="<?php  if (isset(${"Size$i"})) echo ${"Size$i"};?>" style="width:40px"> &nbsp; 
	ComboBox: <input type=text name=IsComboBox<?php  echo $i;?> value="<?php  if (isset(${"IsComboBox$i"})) echo ${"IsComboBox$i"};?>" style="width:200px"><br>
	&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
	Hidden: <input type=text name=Hidden<?php  echo $i;?> value="<?php  if (isset(${"Hidden$i"})) echo ${"Hidden$i"};?>" style="width:40px"> &nbsp; <br>
<?php  }?>
<br>
<input type=button value="Add Column" onClick="AddColumn(<?php  echo ($cols+1);?>);"> &nbsp; 
<input type=button value="Create page" onClick="Create();"> &nbsp; 
</form>